package com.gs.wzweather.service.impl;

import com.gs.wzweather.service.SevereWeatherService;
import com.gs.wzweather.utils.*;
import com.gs.wzweather.vo.StormMessageVO;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Legolas
 * Date: 2017/11/8 0008
 */
@Service
public class SevereWeatherServiceImpl implements SevereWeatherService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public List<String> getRain1ImgNames() {
        List<String> fileNames = new LinkedList<>();
        Map map = DateUtil.getYearMonthDay();
        String rootPath = Constant.FtpFilePath.PRECIPITATION_IMG_RAIN1_ROOTPATH + map.get("year") + "/" + map.get("month") + "/" + map.get("day") + "/";

        FTPClient ftpClient =  FTPUtil.getFTPClient(Constant.FtpFilePath.PRECIPITATION_IMG_RAIN_HOST,Constant.FtpFilePath.FTP_PORT,Constant.FtpFilePath.PRECIPITATION_IMG_RAIN_USERNAME,Constant.FtpFilePath.PRECIPITATION_IMG_RAIN_PASSWORD);
        try {
            if(!ftpClient.changeWorkingDirectory(rootPath)){
                logger.info("getRain1ImgNames切换目录失败->{}");
            }
            else {
                ftpClient.enterLocalPassiveMode();
                FTPFile[] files = ftpClient.listFiles("",(FTPFile ftpFile)->(ftpFile.getName().endsWith(".png")));
                for(FTPFile file:files){
                    if(file.isFile()){
                        fileNames.add(file.getName());
                    }
                }
                return fileNames;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            FTPUtil.closeFtpClient(ftpClient);
        }

        return null;
    }

    public List<String> getRain3ImgNames() {
        List<String> fileNames = new LinkedList<>();
        Map map = DateUtil.getYearMonthDay();
        String rootPath = Constant.FtpFilePath.PRECIPITATION_IMG_RAIN3_ROOTPATH + map.get("year") + "/" + map.get("month") + "/" + map.get("day") + "/";

        FTPClient ftpClient =  FTPUtil.getFTPClient(Constant.FtpFilePath.PRECIPITATION_IMG_RAIN_HOST,Constant.FtpFilePath.FTP_PORT,Constant.FtpFilePath.PRECIPITATION_IMG_RAIN_USERNAME,Constant.FtpFilePath.PRECIPITATION_IMG_RAIN_PASSWORD);
        try {
            if(!ftpClient.changeWorkingDirectory(rootPath)){
                logger.info("getRain3ImgNames切换目录失败->{}");
            }
            else {
                ftpClient.enterLocalPassiveMode();
                FTPFile[] files = ftpClient.listFiles("",(FTPFile ftpFile)->(ftpFile.getName().endsWith(".png")));
                for(FTPFile file:files){
                    if(file.isFile()){
                        fileNames.add(file.getName());
                    }
                }
                return fileNames;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            FTPUtil.closeFtpClient(ftpClient);
        }
        return null;
    }

    public void getRain1Img(String imgName , HttpServletResponse response){
        Map map = DateUtil.getYearMonthDay();
        String rootPath = Constant.FtpFilePath.PRECIPITATION_IMG_RAIN1_ROOTPATH + map.get("year") + "/" + map.get("month") + "/" + map.get("day") + "/";

        FTPClient ftpClient =  FTPUtil.getFTPClient(Constant.FtpFilePath.PRECIPITATION_IMG_RAIN_HOST,Constant.FtpFilePath.FTP_PORT,Constant.FtpFilePath.PRECIPITATION_IMG_RAIN_USERNAME,Constant.FtpFilePath.PRECIPITATION_IMG_RAIN_PASSWORD);

        try {
            if(!ftpClient.changeWorkingDirectory(rootPath)){
                logger.info("getRain1Img切换目录失败->{}");
            }
            else {
                ftpClient.enterLocalPassiveMode();
                InputStream is = ftpClient.retrieveFileStream(imgName);
                HttpUtils.FileResponse(is,response);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            FTPUtil.closeFtpClient(ftpClient);
        }

    }

    public void getRain3Img(String imgName , HttpServletResponse response){
        Map map = DateUtil.getYearMonthDay();
        String rootPath = Constant.FtpFilePath.PRECIPITATION_IMG_RAIN3_ROOTPATH + map.get("year") + "/" + map.get("month") + "/" + map.get("day") + "/";

        FTPClient ftpClient =  FTPUtil.getFTPClient(Constant.FtpFilePath.PRECIPITATION_IMG_RAIN_HOST,Constant.FtpFilePath.FTP_PORT,Constant.FtpFilePath.PRECIPITATION_IMG_RAIN_USERNAME,Constant.FtpFilePath.PRECIPITATION_IMG_RAIN_PASSWORD);

        try {
            if(!ftpClient.changeWorkingDirectory(rootPath)){
                logger.info("getRain3Img切换目录失败->{}");
            }
            else {
                ftpClient.enterLocalPassiveMode();
                InputStream is = ftpClient.retrieveFileStream(imgName);
                HttpUtils.FileResponse(is,response);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            FTPUtil.closeFtpClient(ftpClient);
        }
    }

    @Override
    public StormMessageVO getStorm() {
        String rootPath = Constant.FtpFilePath.STORM_ROOTPATH;

        FTPClient ftpClient =  FTPUtil.getFTPClient(Constant.FtpFilePath.STORM_HOST,Constant.FtpFilePath.FTP_PORT,Constant.FtpFilePath.STORM_USERNAME,Constant.FtpFilePath.STORM_PASSWORD);

        try {
            if(!ftpClient.changeWorkingDirectory(rootPath)){
                logger.info("getStorm切换目录失败->{}");
            }
            else {
                ftpClient.enterLocalPassiveMode();
                FTPFile[] files = ftpClient.listFiles("",(FTPFile ftpFile)->(ftpFile.getName().endsWith(".txt")));
                if (files != null && files.length > 0) {
                    FileSortUtil.OrderByDate(files);
                }
                FTPFile aimFile = files[0];

                InputStream is = ftpClient.retrieveFileStream(aimFile.getName());
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String result="";
                String line;
                while((line=br.readLine())!=null){
                    result+=line;
                    br.readLine();
                }
                return new StormMessageVO(aimFile.getName().substring(0,aimFile.getName().length()-4),result);
            }
        }
        catch (IOException e) {
                e.printStackTrace();
            }
        finally {
            FTPUtil.closeFtpClient(ftpClient);
        }

        return null;
    }

}